import useAmis from '@/hooks/useAmis';
import {createResourceCrudTable} from '@/utils/amisUtils';
import useElectron from "@/hooks/useElectron.tsx";
import useReq from "@/hooks/useReq.tsx";

interface OptionProps {
  id?: string;
  name: string;
}

interface AttrProps {
  id?: string;
  name: string;
  optionList: OptionProps[];
}

function composeData(attrList: AttrProps[]): {label:string, value: string[]}[] {
  if (attrList.length == 0) {
    return [];
  }

  const headAttr = attrList[0];
  const headOptionList = headAttr.optionList;
  if (!headOptionList) {
    return []
  }
  if (attrList.length == 1) {
    return headOptionList.map(opt => ({label: `${headAttr.name}:${opt.name}`, value:[opt.id ?? '']}))
  }

  const restAttrList = attrList.slice(1);
  const restComposeData = composeData(restAttrList);

  return headOptionList.flatMap(opt => restComposeData.map(item => ({label: `${headAttr.name}:${opt.name}, ${item.label}`, value:[opt.id??'', ...item.value]})))
}

let preFormData = {};

const Page = () => {
  const {spider1688} = useElectron();
  const {request} = useReq();
  const json = createResourceCrudTable({
    formId: 'crudForm',
    resourceName: 'products',
    tableBtnList:[
      {
        "label": "爬取1688",
        "type": "button",
        "actionType": "drawer",
        "drawer": {
          title: "爬取1688",
          overlay: true,
          showCloseButton: false,
          body: {
            "type": "form",
            "body": [
              {
                'type': 'textarea',
                'name': 'url',
                'placeholder': '目前只支持一个URL',
                'label': '1688链接',
              }
            ],
            onEvent: {
              submit: {
                actions: [
                  {
                    "script": async (_1: object, _2: object, event: {data: {url: string}}) => {
                      const url = event.data.url;
                      if (!url || !url.startsWith('https://detail.1688.com/')) {
                        throw new Error('目前只支持1688链接');
                      }
                      const resp:Record<string, string> = await spider1688(url);
                      await request('/api/v1/products/importFrom1688', { method: 'POST', data:resp})
                    },
                    "actionType": "custom"
                  },
                ]
              }
            }
          }
        }
      },
    ],
    itemColumns: [
      {
        'name': 'name',
        'label': '产品名',
        "width": 350,
        'searchable': {
          'type': 'input-text',
          'placeholder': '请输入',
          'mode': 'horizontal',
        },
      },
      {
        'name': '${DECODEJSON(mainImage)[0]}',
        'label': '产品主图',
        'type': 'image',
        "enlargeAble": true
      },
    ],
    onFormEvent: {
      change: {
        actions: [
          {
            "actionType": "custom",
            "script": (_: object, doAction: (o:object) => void,event: {data: {attrList: AttrProps[]}})=> {
              const data = event.data;
              if (data.attrList) {
                if (JSON.stringify(preFormData) == JSON.stringify(data.attrList)) {
                  return;
                }
                preFormData = data.attrList
                const attrList = composeData(data.attrList)
                console.log(attrList)
                const setDataAction = {
                  actionType: 'reload',
                  componentId: "attrOptionService2",
                  data: {
                    selectData2: attrList
                  }
                }
                doAction(setDataAction)
              }
            }
          }
        ]
      }
    },
    detailColumns: [
      {
        "type": "tabs",
        "tabsMode": "tiled",
        "data": {
          testList: []
        },
        "tabs": [
          {
            "title": "基础信息",
            "body": [
              {
                'type': 'input-text',
                'name': 'name',
                'label': '产品名',
              },
              {
                "type": "input-tag",
                "name": "tags",
                "label": "标签",
                "placeholder": "请选择标签",
                "options": [
                  "重要",
                  "待办",
                  "关注",
                ]
              },
              {
                'type': 'input-image',
                'name': 'mainImage',
                "receiver": "/api/v1/files/upload",
                autoUpload: false,
                'label': '产品图',
                "multiple": true,
                "draggable": true
              },
              {
                'type': 'input-text',
                'name': 'basePrice',
                'label': '价格区间',
              },
              {
                'type': 'input-text',
                'name': 'unit',
                'label': '单位',
              },
              {
                "type": "json-schema",
                "name": "specDetail",
                "label": "产品属性",
                "schema": {
                  "type": "array",
                  "title": "属性",
                  "items": {
                    "type": "object",
                    "properties": {
                      "name": "string",
                      "value": "string"
                    }
                  },
                }
              },
              {
                'type': 'input-rich-text',
                'name': 'intro',
                'label': '产品描述',
                "receiver": "/api/v1/files/upload",
                "options": {
                  "menubar": false,
                  "height": 550,
                }
              },
              {
                "type": "input-file",
                "name": "files",
                "label": "资质文件",
                "accept": "*",
                "receiver": "/api/v1/files/upload",
                "multiple": true,
                "joinValues": false,
                autoUpload: false,
                "onEvent": {
                  "success": {
                    "actions": [
                      {
                        "actionType": "toast",
                        "args": {
                          "msgType": "info",
                          "msg": "「${event.data.path}」上传成功"
                        }
                      }
                    ]
                  }
                }
              },
            ]
          },
          {
            title: '属性信息',
            body: [
              {
                "type": "combo",
                "name": "attrList",
                "label": false,
                "multiple": true,
                "items": [
                  {
                    "name": "id",
                    "type": "hidden"
                  },
                  {
                    "name": "name",
                    "label": "属性",
                    "type": "input-text"
                  },
                  {
                    "type": "combo",
                    "name": "optionList",
                    "label": false,
                    "multiple": true,
                    "items": [
                      {
                        "name": "id",
                        "type": "hidden"
                      },
                      {
                        "name": "name",
                        "label": "选项",
                        "type": "input-text"
                      },
                    ],
                    onEvent: {
                      add: {
                        actions: [
                          {
                            "actionType": "ajax",
                            "api": {
                              "url": "/api/v1/common/genID",
                              "method": "post",
                              "silent": true
                            },
                            "data": {
                              "id": "123456"
                            }
                          },
                          {
                            "actionType": "setValue",
                            "componentName": "id",
                            "args": {
                              "value": "${id}"
                            }
                          }
                        ]
                      }
                    }
                  }
                ]
              }
            ]
          },
          {
            "title": "SKU信息",
            "body": [
              {
                "type": "combo",
                "name": "skuList",
                "label": false,
                "multiple": true,
                "multiLine": true,
                "tabsMode": true,
                "tabsStyle": "card",
                "tabsLabelTpl": "${name}",
                "items": [
                  {
                    type: 'service',
                    id: "attrOptionService2",
                    body: {
                      "label": "属性选项",
                      "type": "select",
                      "name": "attrOption2",
                      "searchable": true,
                      "source": "${selectData2}",
                    },
                  },
                  {
                    "type": "input-text",
                    "name": "name",
                    "label": "SKU名称",
                    "required": true
                  },
                  {
                    "type": "input-number",
                    "name": "price",
                    "label": "价格",
                    "precision": 2,
                    "step": 0.1,
                    "unitOptions": [
                      "RMB",
                    ]
                  },
                  {
                    'type': 'input-image',
                    'name': 'imageList',
                    "receiver": "/api/v1/files/upload",
                    autoUpload: false,
                    'label': '产品图',
                    "multiple": true,
                    "draggable": true
                  },
                ]
              }
            ]
          },
        ]
      },
    ],
  });

  const AmisComponent = useAmis({
    'type': 'page',
    'id': 'ppp',
    'data': {
      selectData: [
        {label: '选项1', value: '1'}, {label: '选项2', value: '2'}
      ]
    },
    'body': [
      json,
    ]
  });

  return (
    <div>
      <AmisComponent />
    </div>
  );
}
export default Page;